<template>
  <div v-if="formData && formFields.length" class="ind-post-form-edit">
    <el-form
      v-if="formFields.length"
      :model="formData"
      ref="postForm"
      label-position="left"
      :label-width="labelWidth"
      :rules="formRules"
      size="small"
      :disabled="disabled"
      class="post-form">
      <el-form-item v-for="item in formFields" :key="item.fillId" :label="item.title" :prop="item.fillId">
        <el-input
          v-if="item.config.type === FIELD_TYPE.text"
          :maxlength="1000"
          type="textarea"
          autosize
          clearable
          v-model="formData[item.fillId].value"
          @change="onFieldChange(item.fillId)"></el-input>
        <upload-file
          v-else-if="item.config.type === FIELD_TYPE.file"
          :file-list="formData[item.fillId].value"
          :disabled="disabled"
          :max-limit="20"
          @change="onFieldChange(item.fillId)"></upload-file>
        <el-date-picker
          v-else-if="item.config.type === FIELD_TYPE.date"
          v-model="formData[item.fillId].value"
          type="date"
          placeholder="请选择日期"
          value-format="yyyy-MM-dd"
          :picker-options="getPickerOptions(item)"
          @change="onFieldChange(item.fillId)"></el-date-picker>
        <!-- <el-rate v-else-if="item.config.type === FIELD_TYPE.rate" v-model="formData[item.fillId].value" @change="onFieldChange(item.fillId)"></el-rate> -->
        <org-rate
          v-else-if="item.config.type === FIELD_TYPE.rate"
          v-model="formData[item.fillId].value"
          @change="onFieldChange(item.fillId)"></org-rate>
        <el-slider
          v-else-if="item.config.type === FIELD_TYPE.slider"
          v-model="formData[item.fillId].value"
          :format-tooltip="tooltipFormat"
          @change="onFieldChange(item.fillId)"></el-slider>
        <el-select
          v-else-if="item.config.type === FIELD_TYPE.orgSelector"
          v-model="formData[item.fillId].value"
          placeholder="请选择"
          filterable
          clearable
          @change="onFieldChange(item.fillId)">
          <el-option
            v-for="item in indOrgs"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="selectedOrgs.includes(item.value)"></el-option>
        </el-select>
        <el-radio-group
          v-else-if="item.config.type === FIELD_TYPE.fromShareInner"
          v-model="formData[item.fillId].value"
          @change="onFieldChange(item.fillId)">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div class="add-view" v-if="!disabled && showAdd">
      <div class="add-btn" title="点击新增表单" @click.stop="addFormItem">+ 新增</div>
    </div>
    <div class="delete-view" v-if="!disabled && showDelete">
      <el-popconfirm
        confirm-button-text="确定"
        cancel-button-text="取消"
        icon="el-icon-info"
        icon-color="#E6A23C"
        title="确定要删除该表单吗？"
        @confirm="deleteFormItem">
        <i class="el-icon-delete" slot="reference"></i>
      </el-popconfirm>
    </div>
  </div>
</template>

<script>
import { IND_POST_TYPE } from '@utility/dict'
import UploadFile from '@com/UploadFile'
import OrgRate from './OrgRate.vue'
export default {
  name: 'PostFormEdit',
  components: { UploadFile, OrgRate },
  inject: ['formValid'],
  props: {
    fields: {
      type: Array,
    },
    fieldData: {
      // 已填报的数据
      type: Array,
    },
    disabled: {
      type: Boolean,
    },
    formIdx: {
      type: Number,
    },
    labelMinWidth: {
      type: Number,
    },
    showAdd: {
      type: Boolean,
    },
    showDelete: {
      type: Boolean,
    },
    pid: {
      type: String, // 用于org selector 互斥操作
    },
    id: {
      type: String, // form 唯一id
    },
    shareCount: {
      type: Number,
    },
  },
  data() {
    return {
      formData: null,
      FIELD_TYPE: IND_POST_TYPE._define,
      oldOrgId: null,
    }
  },
  computed: {
    labelWidth() {
      if (this.formFields && this.formFields.length) {
        let maxlength = 0
        this.formFields.forEach(item => {
          if (item.title.length > maxlength) {
            maxlength = item.title.length
          }
        })
        let labelWidth = Math.ceil(maxlength * 19) + 20
        if (labelWidth < 120) {
          labelWidth = 120
        }
        if (this.labelMinWidth && labelWidth < this.labelMinWidth) {
          labelWidth = this.labelMinWidth
        }
        this.$emit('label-width', labelWidth)
        return labelWidth + 'px'
      }
      return '80px'
    },
    indOrgs() {
      return this.$store.getters['indPush/indEvaOrgs']
    },
    selectedOrgs() {
      if (this.pid) {
        return this.$store.getters['indPush/selectedOrgIds'](this.pid)
      }
      return []
    },
    formFields() {
      // if (this.shareCount > 0) {
      //   return this.fields.filter(item => item.config.type !== IND_POST_TYPE.fromShare && item.config.isNeed === '1')
      // }
      return this.fields.filter(item => item.config.type !== IND_POST_TYPE.fromShare)
    },
    formRules() {
      const formRules = {}
      if (this.fields) {
        this.fields.forEach(item => {
          if (item.config.isWrite === '1') {
            formRules[item.fillId] = {
              required: true,
              trigger: (item.config.type === IND_POST_TYPE.text && 'blur') || 'change',
              validator: (rule, value, callback) => {
                if ((value.value !== 0 && !value.value) || (Array.isArray(value.value) && value.value.length === 0)) {
                  callback(new Error(item.title + '不能为空'))
                }
              },
            }
          }
        })
      }
      return formRules
    },
  },
  watch: {
    fields(val) {
      this.initFormData(val)
    },
    formValid: {
      deep: true,
      handler(val) {
        if (!val.check) {
          this.$refs.postForm && this.$refs.postForm.clearValidate()
        } else if ((val.scope.includes(this.id) || val.scope === 'all') && val.check) {
          this.checkFormValid()
        }
      },
    },
    shareCount() {
      this.$refs.postForm && this.$refs.postForm.clearValidate()
    },
  },
  created() {},
  mounted() {
    if (this.fields && this.fields.length) {
      this.initFormData(this.fields)
    }
    console.log('forms...', this.formFields)
  },
  methods: {
    initFormData(fields) {
      if (fields) {
        const formData = {}
        fields.forEach(item => {
          formData[item.fillId] = { value: '', config: item.config }

          let dataItem = null
          if (this.fieldData) {
            dataItem = this.fieldData.find(dItem => dItem.fillId === item.fillId)
          }
          if (item.config.type === IND_POST_TYPE.file) {
            formData[item.fillId].value = (dataItem && dataItem.fileShowList) || []
          } else if ([IND_POST_TYPE.rate, IND_POST_TYPE.slider].includes(item.config.type)) {
            formData[item.fillId].value = (dataItem && dataItem.content - 0) || 0
          } else if (item.config.type === IND_POST_TYPE.fromShare) {
            formData[item.fillId].value = (dataItem && dataItem.content) || '0'
          } else {
            formData[item.fillId].value = (dataItem && dataItem.content) || ''
          }
          if (item.config.type === IND_POST_TYPE.orgSelector && dataItem && dataItem.content) {
            this.updateOrgs(dataItem.content)
          }
        })
        this.$emit('change', formData)
        this.formData = formData
      }
    },
    tooltipFormat(val) {
      return val + ' %'
    },
    onFieldChange(filedId) {
      const field = this.fields.find(item => item.fillId === filedId)

      const val = this.formData[filedId].value
      if (field.config && field.config.isWrite === '1') {
        // 非空校验
        if (field.config.type === IND_POST_TYPE.file) {
          if (val.length > 0) {
            this.$emit('change', this.formData, filedId)
          }
          this.$refs.postForm.validateField(filedId)
        } else if (val !== '') {
          this.$emit('change', this.formData, filedId)
        }
      } else {
        this.$emit('change', this.formData, filedId)
      }
      // org 重复选择控制
      if (field.config.type === IND_POST_TYPE.orgSelector) {
        this.updateOrgs(val)
      }
    },
    updateOrgs(val) {
      if (this.oldOrgId) {
        // remove cache
        this.$store.commit('indPush/removeSelectOrgs', { pid: this.pid, orgId: this.oldOrgId })
      }
      if (val) {
        // set cache
        this.$store.commit('indPush/setSelectOrgs', { pid: this.pid, orgId: val })
      }
      this.oldOrgId = val
    },
    checkFormValid() {
      if (!this.disabled) {
        this.$refs.postForm.validate()
      }
    },
    addFormItem() {
      this.$emit('form-add')
    },
    deleteFormItem() {
      this.$emit('form-delete')
    },
    getPickerOptions(item) {
      const { minDate, maxDate } = item.config
      let minLimit = null
      let maxLimit = null
      if (minDate) {
        minLimit = this.parseLimitDate(minDate)
      }
      if (maxDate) {
        maxLimit = this.parseLimitDate(maxDate)
      }
      return {
        disabledDate(time) {
          return (minLimit && time.getTime() < minLimit) || (maxLimit && time.getTime() > maxLimit)
        },
      }
    },
    parseLimitDate(date) {
      let limitDate = null
      const suffixMatch = /day|month|year$/.exec(date)
      if (suffixMatch) {
        const type = suffixMatch[0]
        const val = date.substring(0, suffixMatch.index)
        const valNum = Number(val)
        if (isNaN(valNum)) {
          return {}
        }
        const nowDate = new Date()
        const nowDay = nowDate.getDate()
        const nowMonth = nowDate.getMonth()
        const nowYear = nowDate.getFullYear()
        switch (type) {
          case 'day':
            limitDate = nowDate.setDate(nowDay + valNum)
            break
          case 'month':
            limitDate = nowDate.setMonth(nowMonth + valNum)
            break
          case 'year':
            limitDate = nowDate.setMonth(nowYear + valNum)
            break
          default:
            break
        }
      }
      return limitDate
    },
  },
}
</script>
<style lang="scss" scoped>
.ind-post-form-edit {
  position: relative;
  padding-right: 10px;
  &:not(:first-child) {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px dashed #ddd;
  }
  ::v-deep .post-form {
    .el-form-item__label {
      font-size: 16px;
      font-weight: bold;
    }
    .el-form-item {
      &:last-child {
        margin-bottom: 0;
      }
    }
    .el-rate {
      margin-top: 6px;
      i {
        font-size: 24px;
      }
    }
    .el-input--small {
      font-size: 16px;
    }
  }
  .add-view {
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    .add-btn {
      margin-right: 10px;
      color: #2c63b0;
      cursor: pointer;
    }
  }
  .delete-view {
    position: absolute;
    right: -10px;
    top: 0px;
    font-size: 14px;
    color: #f56c6c;
    cursor: pointer;
  }
}
</style>
